import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_web_study/api/dio_utils.dart';
import 'package:flutter_web_study/api/service_api.dart';
import 'package:flutter_web_study/utils/toast_utils.dart';
import 'package:logger/logger.dart';
import 'dart:html' as html;
import '../api/app_config.dart';
import '../bean/menu_item.dart';
import '../page/weight/text_field_input_widget.dart';
import '../router/application.dart';
import '../router/routes.dart';

class NewShopViewModel extends ChangeNotifier {
  TextEditingController textEditingController1 = TextEditingController();
  TextEditingController textEditingController2 = TextEditingController();
  TextEditingController textEditingController3 = TextEditingController();
  TextEditingController textEditingController4 = TextEditingController();
  TextEditingController textEditingController5 = TextEditingController();
  TextEditingController textEditingController6 = TextEditingController();
  TextEditingController textEditingController7 = TextEditingController();
  TextEditingController textEditingController8 = TextEditingController();
  TextEditingController textEditingController9 = TextEditingController();
  TextEditingController textEditingController10 = TextEditingController();
  TextEditingController textEditingController11 = TextEditingController();
  TextEditingController textEditingController12 = TextEditingController();

  MenuItemBean menuItemBean =
      MenuItemBean(value: 0, label: "全部", checked: false);

  String? jsonBean = "";

  //成分
  TextEditingController textEditingController13 = TextEditingController();

  BuildContext me;

  NewShopViewModel(this.me, this.jsonBean);

  //功效集合
  List effectList = [];

  //商品标签集合
  List shopTagList = [];

  //图片集合
  List<dynamic> imageList = [];
  List<dynamic> imageDerivative = [];

  String goodsId = "";
  String jdGoodsId = "";
  String pddGoodsId = "";
  String tBGoodsId = "";
  int id = 0;

  initView() {
    if (jsonBean != null) {
      Logger().d(jsonDecode(jsonBean!));
      Map jsonMap = jsonDecode(jsonBean!);
      goodsId = jsonMap["goodsId"];

      brandTypeList.forEach((element) {
        if (jsonMap["kind"] == element.value) {
          menuItemBean = element;
        }
      });

      // {
      //        "id": 252,
      id = jsonMap["id"];
      //        "goodsId": "63fc2a1a7b7bc225440d0ffd",
      goodsId = jsonMap["goodsId"] ?? "";
      //        "jdGoodsId": "",
      jdGoodsId = jsonMap["jdGoodsId"] ?? "";
      //        "pddGoodsId": "",
      pddGoodsId = jsonMap["pddGoodsId"] ?? "";
      //        "tBGoodsId": "",
      tBGoodsId = jsonMap["tBGoodsId"] ?? "";
      //        "kind": 3,
      //        "tag": [],
      shopTagList = jsonMap["tag"];
      //        "brand": 0,
      //        "brandName": "滋色",
      textEditingController1.text = jsonMap["brandName"];
      //        "brandEnName": "ZEESEA",
      textEditingController2.text = jsonMap["brandEnName"];
      //        "series": "纤细睫毛膏",
      textEditingController3.text = jsonMap["series"];
      //        "seriesEn": "",
      textEditingController4.text = jsonMap["seriesEn"];
      //        "color": "黑色",
      textEditingController5.text = jsonMap["color"];
      //        "colorEn": "",
      textEditingController6.text = jsonMap["colorEn"];
      //        "imageList": [
      //          "upload/纤细睫毛膏.jpg"
      //        ],
      imageList = jsonMap["imageList"];
      //        "deriveImageList": [],
      imageDerivative = jsonMap["deriveImageList"];
      //        "price": "39.9",
      textEditingController8.text = jsonMap["price"];
      //        "madeIn": "中国",
      textEditingController9.text = jsonMap["madeIn"];
      //        "ingredient": "",
      textEditingController13.text = jsonMap["ingredient"];
      //        "netContent": "4ml",
      textEditingController7.text = jsonMap["netContent"];
      //        "gradeScore": "",
      textEditingController10.text = jsonMap["gradeScore"];
      //        "efficacy": [
      //          "卷翘",
      //          "浓密",
      //          "纤长"
      //        ],
      effectList = jsonMap["efficacy"];
      //        "linkGoodsList": [],
      //        "recordNo": "",
      textEditingController11.text = jsonMap["recordNo"];
      //        "updateTime": 1677470234055
      //      }

      // "brand": 0,
      notifyListeners();
    }
    getRelationDate();
  }

  initData() {}

  Future<void> getLostData(String str) async {
    html.FileUploadInputElement uploadInput = html.FileUploadInputElement();
    uploadInput.multiple = false; // 是否允许选择多文件
    uploadInput.draggable = true;
    uploadInput.click();
    uploadInput.onChange.listen((event) {
      // 选择完成
      html.File? file = uploadInput.files?.first;
      print('文件大小：${file?.size}');
      print('name:${file?.name}');
      if (file != null) {
        print('开始上传');
        html.FormData formData = html.FormData();
        formData.appendBlob('file', file.slice(), file.name);
        if (str == "衍生图:") {
          formData.append('folder', "derive");
        }
        print('上传文件到服务器');
        // 上传文件到服务器
        var request = html.HttpRequest();
        request.open('POST', AppConfig.BASE_URL + ServiceApi.UPLOAD_FILE);
        request.send(formData);
        print('发送了');
        request.onLoadEnd.listen((event) {
          print('上传结果：${request.responseText}');
          if (request.responseText != null) {
            Map<String, dynamic> map = jsonDecode("${request.responseText}");
            if (map["code"] == 0) {
              if (str == "衍生图:") {
                imageDerivative.add(map["data"]);
              } else {
                imageList.add(map["data"]);
              }
              notifyListeners();
            }
          }
        });
      }
    });
  }

  List<dynamic> getImageList(String str) {
    return str == "衍生图:" ? imageDerivative : imageList;
  }

  //shop 是true 功效是 false
  deleteLabe(isShop, index) {
    // List effectList = [];
    //商品标签集合
    // List shopTagList = [];
    if (isShop) {
      shopTagList.removeAt(index);
    } else {
      effectList.removeAt(index);
    }
    notifyListeners();
  }

  getMenuItemBean(String value) {
    Logger().d(value);
    brandTypeList.forEach((element) {
      if (value == element.label) {
        menuItemBean = element;
      }
    });
    notifyListeners();
  }

  //保存商品
  saveShop(BuildContext context) {
    var linkGoodsList = [];
    if (relationShop.length > 0) {
      relationShop.forEach((element) {
        linkGoodsList.add(element["goodsId"]);
      });
    }
    var json = {
      "id": id,
      "jdGoodsId": jdGoodsId,
      "pddGoodsId": pddGoodsId,
      "tBGoodsId": tBGoodsId,
      "goodsId": goodsId ?? "",
      //分类
      "kind": menuItemBean.value,
      //商品标签
      "tag": shopTagList,
      // //名称
      // "name": "",
      // //英文名称
      // "enName": "",
      //品牌id
      "brand": 0,
      //品牌名称
      "brandName": textEditingController1.text.toString().trim(),
      //品牌英文名称
      "brandEnName": textEditingController2.text.toString().trim(),
      //系列
      "series": textEditingController3.text.toString().trim(),
      //系列英文
      "seriesEn": textEditingController4.text.toString().trim(),
      //色号
      "color": textEditingController5.text.toString().trim(),
      //色号英文
      "colorEn": textEditingController6.text.toString().trim(),
      //净含量
      "netContent": textEditingController7.text.toString().trim(),
      //价格
      "price": textEditingController8.text.toString().trim(),
      //产地
      "madeIn": textEditingController9.text.toString().trim(),
      //评分
      "gradeScore": textEditingController10.text.toString().trim(),
      //备案号
      "recordNo": textEditingController11.text.toString().trim(),
      //配图列表
      "imageList": imageList,
      "deriveImageList": imageDerivative,
      //成分
      "ingredient": textEditingController13.text.toString().trim(),
      //功效
      "efficacy": effectList,
      //评价
      "comment": [],
      //关联商品列表
      "linkGoodsList": linkGoodsList,
    };

    DioUtils.getInstance()
        ?.post(ServiceApi.addMakeupGoods, {"json": jsonEncode(json)},
            (successCallBack) {
      ToastUtils.showToast(msg: "保存成功");
      Navigator.pop(context, json);
    }, (errorCallBack) {});
  }

  void tagSwitch(int tag) {
    //请求接口
    DioUtils.getInstance()?.post(
        tag == 1
            ? ServiceApi.REQUEST_GOODS_EFFICACY
            : ServiceApi.REQUEST_GOODS_TAG,
        {}, (successCallBack) {
      List<dynamic> list = successCallBack["data"] as List<dynamic>;
      List<String> list2 = [];
      list.forEach((element) {
        list2.add(element["name"]);
      });
      showCheckList(tag, list2);
    }, (errorCallBack) {});
  }

  void showCheckList(int tag, List<String> list) {
    showDialog(
        barrierDismissible: true, //点击灰色背景的时候是否消失弹出框
        context: me,
        builder: (context) {
          return StatefulBuilder(builder: (context, state) {
            return AlertDialog(
              title: Text(tag == 1 ? "请选择功效" : "请选择商品"),
              content: SingleChildScrollView(
                child: ListBody(
                  children: list
                      .map((item) => CheckboxListTile(
                            value: tag == 1
                                ? effectList.contains(item)
                                : shopTagList.contains(item),
                            title: Text(item),
                            secondary: IconButton(
                              icon: Icon(Icons.delete),
                              onPressed: () {
                                list.remove(item);
                                deletePost(tag, item);
                                state(() {});
                              },
                            ),
                            controlAffinity: ListTileControlAffinity.leading,
                            onChanged: (isChecked) {
                              if (tag == 1) {
                                if (effectList.contains(item)) {
                                  effectList.remove(item);
                                } else {
                                  effectList.add(item);
                                }
                              } else {
                                if (shopTagList.contains(item)) {
                                  shopTagList.remove(item);
                                } else {
                                  shopTagList.add(item);
                                }
                              }
                              notifyListeners();
                              state(() {});
                            },
                          ))
                      .toList(),
                ),
              ),
              actions: [
                TextButton(
                  child: const Text('取消'),
                  onPressed: () {
                    notifyListeners();
                    Navigator.pop(context);
                  },
                ),
              ],
            );
          });
        });
  }

  //删除标签
  void deletePost(int tag, String value) {
    DioUtils.getInstance()?.post(
        tag == 1
            ? ServiceApi.REMOVE_GOODS_EFFICACY
            : ServiceApi.REMOVE_GOODS_TAG,
        {(tag == 1 ? "efficacy" : "tag"): value},
        (successCallBack) {},
        (errorCallBack) {});
  }

  //1功效 2 商品
  void addTagSwitch(int tag) {
    showDialog(
        barrierDismissible: false, //点击灰色背景的时候是否消失弹出框
        context: me,
        builder: (context) {
          TextEditingController controller = TextEditingController();
          return AlertDialog(
            title: Text(tag == 1 ? "请输入功效标签" : "请输入商品标签"),
            content: TextFieldInputWidget(
              hitTextStr: '请输入标签',
              controller: controller,
            ),
            actions: <Widget>[
              FilledButton(
                child: const Text("cancel"),
                onPressed: () => Navigator.pop(context),
              ),
              FilledButton(
                child: const Text("OK"),
                onPressed: () {
                  var map = {
                    (tag == 1 ? "efficacy" : "tag"):
                        controller.text.trim().toString()
                  };
                  DioUtils.getInstance()?.post(
                      tag == 1
                          ? ServiceApi.ADD_GOODS_EFFICACY
                          : ServiceApi.ADD_GOODS_TAG,
                      map, (successCallBack) {
                    ToastUtils.showToast(msg: successCallBack["message"]);
                    Navigator.pop(context);
                  }, (errorCallBack) {
                    ToastUtils.showToast(msg: errorCallBack["message"]);
                  });
                },
              )
            ],
          );
        });
  }

  jumpSearchPage() {
    Application().navigatePushToPage(
        me, Routes.searchPage, {"tagPage": "0", "value": ""}).then((value) {
      if (value["name"] != null) {
        textEditingController1.text = value["name"];
      } else {
        Map jsonMap = value["tag"];
        brandTypeList.forEach((element) {
          if (jsonMap["kind"] == element.value) {
            menuItemBean = element;
          }
        });
        shopTagList = jsonMap["tag"];
        // "brand": 0,
        // "brandName": "测试商品1",
        textEditingController1.text = jsonMap["brandName"];
        // "brandEnName": "ceshi1",
        textEditingController2.text = jsonMap["brandEnName"];
        // "series": "系列名称",
        textEditingController3.text = jsonMap["series"];
        // "seriesEn": "xielie",
        textEditingController4.text = jsonMap["seriesEn"];
        // "color": "色号名称1",
        textEditingController5.text = jsonMap["color"];
        // "colorEn": "sehao",
        textEditingController6.text = jsonMap["colorEn"];
        // "imageList": [
        //   "upload/image2.webp"
        // ],
        imageList = jsonMap["imageList"];
        // "deriveImageList": [],
        // "price": "100",
        textEditingController8.text = jsonMap["price"];
        // "madeIn": "山西研究呢成",
        textEditingController9.text = jsonMap["madeIn"];
        // "ingredient": "人参",
        textEditingController13.text = jsonMap["ingredient"];
        // "netContent": "10",
        textEditingController7.text = jsonMap["netContent"];
        // "gradeScore": "10",
        textEditingController10.text = jsonMap["gradeScore"];
        // "efficacy": [
        //   "33333",
        //   "11111"
        // ],
        effectList = jsonMap["efficacy"];
        // "linkGoodsList": [],
        // "recordNo": "1218212121212"
        textEditingController11.text = jsonMap["recordNo"];
      }
      notifyListeners();
    });
  }

  //系列的跳转
  jumpSearch2Page() {
    Application().navigatePushToPage(me, Routes.searchPage, {
      "tagPage": "1",
      "brand": "${textEditingController1.text.toString().trim()}"
    }).then((value) {
      textEditingController3.text = value["name"];
      notifyListeners();
    });
  }

  //色号
  jumpSearch3Page() {
    Application().navigatePushToPage(me, Routes.searchPage, {
      "tagPage": "2",
      "brand": "${textEditingController1.text.toString().trim()}",
      "series": "${textEditingController3.text.toString().trim()}"
    }).then((value) {
      textEditingController5.text = value["name"];
      notifyListeners();
    });
  }

  List relationShop = [];
  List listShopAll = [];
  var sumNumber = 1;

  int page = 1;

  getRelationDate() {
    // 请求接口
    DioUtils.getInstance()?.post(ServiceApi.QUERY_MAKEUP_GOODS, {
      "page": page,
      "pageSize": 10,
    }, (successCallBack) {
      listShopAll = successCallBack["data"]["list"];
      sumNumber = successCallBack["data"]["totalPage"];
    }, (errorCallBack) {});
  }

  getRelationShopDialog() {
    if (listShopAll.length > 0) {
      showDialog(
          barrierDismissible: true, //点击灰色背景的时候是否消失弹出框
          context: me,
          builder: (context) {
            return StatefulBuilder(builder: (context, state) {
              return AlertDialog(
                title: Text("请选择关联商品"),
                content: SingleChildScrollView(
                  child: ListBody(
                    children: listShopAll
                        .map((item) => CheckboxListTile(
                              value: relationShop.contains(item),
                              title: Row(
                                children: [
                                  (item["imageList"] as List).length > 0
                                      ? Container(
                                          margin: EdgeInsets.all(5),
                                          width: 100,
                                          height: 100,
                                          child: Image.network(
                                              AppConfig.IMAGE_PREFIX +
                                                  item["imageList"][0]),
                                        )
                                      : Container(),
                                  Text(item["brandName"])
                                ],
                              ),
                              controlAffinity: ListTileControlAffinity.leading,
                              onChanged: (isChecked) {
                                if (relationShop.contains(item)) {
                                  relationShop.remove(item);
                                } else {
                                  relationShop.add(item);
                                }
                                notifyListeners();
                                state(() {});
                              },
                            ))
                        .toList(),
                  ),
                ),
                actions: [
                  TextButton(
                    child: const Text('取消'),
                    onPressed: () {
                      notifyListeners();
                      Navigator.pop(context);
                    },
                  ),
                ],
              );
            });
          });
    } else {
      getRelationDate();
    }
  }

  void deleteImageList(indext, str) {
    getImageList(str).removeAt(indext);
    notifyListeners();
  }

  void relationShopDelete(item) {
    relationShop.remove(item);
    notifyListeners();
  }
}
